<?php

namespace App\Http\Controllers\Wechat\WechatServiceAccount;

use Carbon\Carbon;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\WechatServiceAccountUser;
use App\Models\WechatServiceAccountAddress;
use App\Models\UserToken;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class WechatServiceAccountController extends Controller
{
    /**
     * 显示首页
     */
    public function index()
    {
        $products = Product::where('status', true)
            ->orderBy('created_at', 'desc')
            ->get();

        // 微信分享配置
        $wxConfig = $this->getWxJsConfig();

        return view('wechat.service_account.index', compact('products', 'wxConfig'));
    }

    /**
     * 显示商品详情页
     */
    public function show($id)
    {
        $product = Product::with('media')->findOrFail($id);
    
        // 如果商品不在售，则重定向到首页
        if (!$product->status) {
            return redirect()->route('wechat.service.account.index')
                ->with('error', '该商品已下架');
        }
    
        // 格式化价格，保留两位小数
        $product->formatted_price = number_format($product->price, 2);
    
        // 微信分享配置
        $wxConfig = $this->getWxJsConfig();

        return view('wechat.service_account.product_detail', compact('product', 'wxConfig'));
    }

    /**
     * 显示订单列表
     */
    public function listOrders()
    {
        // 获取当前用户的订单数据
        $user = Auth::guard('wechat')->user();
        
        // 新增：检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试访问订单列表');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 修改：使用分页加载订单数据，排除"未支付"和"已取消"状态的订单，按创建时间倒序排列
        $orders = Order::where('wechat_service_account_user_id', $user->id)
            ->where('status', '!=', '未支付')
            ->where('status', '!=', '已取消')
            ->with('items.product') // 将products改为items.product
            ->orderBy('created_at', 'desc')  // 明确指定按创建时间倒序排列
            ->paginate(10); // 每页10条
    
        return view('wechat.service_account.member_center.orders', compact('orders'));
    }

    /**
     * 显示登录页面
     */
    public function login()
    {
        Log::debug('进入login页面', [
            'check' => Auth::guard('wechat')->check(),
            'user' => Auth::guard('wechat')->user(),
            'session_id' => session()->getId(),
        ]);
        if (Auth::guard('wechat')->check()) {
            // 避免死循环：只跳转到首页或"我的"页面，不跳回login
            return redirect()->route('wechat.service.account.my');
        }
        return view('wechat.service_account.login');
    }

    /**
     * 发起微信授权
     */
    public function auth()
    {
        $appId = config('wechat.app_id', '');
        $redirectUri = urlencode(route('wechat.service.account.callback'));
        $scope = 'snsapi_userinfo'; // 或者使用 snsapi_base 只获取基本信息

        // 构建微信授权URL
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";

        return redirect($url);
    }

    /**
     * 发起微信静默授权（用于扫码直接登录）
     */
    public function silentAuth(Request $request)
    {
        // 获取重定向URL参数
        $redirectUrl = $request->query('redirect');
        
        $appId = config('wechat.app_id', '');
        $redirectUri = urlencode(route('wechat.service.account.silent.callback', ['redirect' => $redirectUrl]));
        $scope = 'snsapi_base'; // 静默授权，只获取openid

        // 构建微信静默授权URL
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";

        return redirect($url);
    }

    /**
     * 处理微信回调
     */
    public function callback(Request $request)
    {
        $code = $request->input('code');
        $state = $request->input('state');

        if (empty($code)) {
            Log::error('微信授权回调失败: 缺少code参数');
            return redirect()->route('wechat.service.account.login')
                ->with('error', '微信授权失败，请重试');
        }

        try {
            // 1. 使用code获取access_token
            $appId = config('wechat.app_id');
            $appSecret = config('wechat.app_secret');
            $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";

            $response = file_get_contents($tokenUrl);
            $tokenData = json_decode($response, true);

            if (isset($tokenData['errcode'])) {
                Log::error('获取微信access_token失败', $tokenData);
                return redirect()->route('wechat.service.account.login')
                    ->with('error', '微信授权失败: ' . $tokenData['errmsg']);
            }

            $accessToken = $tokenData['access_token'];
            $openId = $tokenData['openid'];

            // 2. 使用access_token获取用户信息
            $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
            $userInfoResponse = file_get_contents($userInfoUrl);
            $userInfo = json_decode($userInfoResponse, true);

            if (isset($userInfo['errcode'])) {
                Log::error('获取微信用户信息失败', $userInfo);
                return redirect()->route('wechat.service.account.login')
                    ->with('error', '获取用户信息失败: ' . $userInfo['errmsg']);
            }

            // 3. 处理用户登录/注册逻辑
            $userData = [
                'nickname' => $userInfo['nickname'],
                'avatar' => $userInfo['headimgurl'],
                'gender' => $userInfo['sex'],
                'province' => $userInfo['province'],
                'city' => $userInfo['city'],
                'country' => $userInfo['country'],
                'access_token' => encrypt($tokenData['access_token']),
                'access_token_expires_at' => now()->addHours(2)->subSecond(1),
                'session_key' => $tokenData['session_key'] ?? '',
                'session_expires_at' => now()->addDays(30)
            ];

            // 使用事务确保数据一致性
            DB::transaction(function () use ($openId, $userData, &$user, &$token) { // 添加&$token引用传递
                $user = WechatServiceAccountUser::updateOrCreate(
                    ['openid' => $openId],
                    $userData
                );
                
                // 生成并存储用户Token
                $token = Str::random(60);
                UserToken::updateOrCreate(
                    ['wechat_user_id' => $user->id],
                    [
                        'token' => $token,
                        'expired_at' => now()->addDays(30)
                    ]
                );
            });

            // 记录完整的用户信息
            Log::debug('WeChat User Object Details', [
                'time' => now()->toDateTimeString(),
                'user_id' => $user->id,
                'openid' => $user->openid,
                'user_attributes' => $user->makeHidden([
                    'access_token',
                    'access_token_expires_at'
                ])->toArray(),
                'request_ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ]);

            // 4. 登录用户
            Auth::guard('wechat')->login($user, true);

            // 立即记录登录状态
            Log::debug('After login:', [
                'check' => Auth::guard('wechat')->check(),
                'user' => Auth::guard('wechat')->user(),
                'session_id' => session()->getId(),
            ]);
            
            // 将token存入session以便前端使用
            $request->session()->put('wechat_token', $token);
            
            // 调试日志
            Log::debug('WeChat login status:', [
                'authenticated' => Auth::guard('wechat')->check(),
                'user_id' => Auth::guard('wechat')->id()
            ]);

            // 检查是否有意图访问的URL
            $intendedUrl = session()->pull('url.intended');
            
            // 获取重定向参数
            $redirectParam = $request->query('redirect');
            
            // 优先使用重定向参数，然后是意图URL，最后是默认页面
            if ($redirectParam) {
                $redirectUrl = $redirectParam;
            } elseif ($intendedUrl && strpos($intendedUrl, '/wechat-service-account/redeem') !== false) {
                $redirectUrl = $intendedUrl;
            } else {
                // 默认跳转到"我的"页面
                $redirectUrl = route('wechat.service.account.my');
            }

            Log::debug('Redirecting to:', ['url' => $redirectUrl]);

            // 微信内特殊处理
            if (strpos($request->userAgent(), 'MicroMessenger') !== false) {
                return redirect($redirectUrl);
            }

            return redirect($redirectUrl);
        } catch (\Exception $e) {
            Log::error('微信授权流程异常: ' . $e->getMessage());
            return redirect()->route('wechat.service.account.login')
                ->with('error', '微信授权异常，请重试');
        }
    }

    /**
     * 处理微信静默授权回调（用于扫码直接登录）
     */
    public function silentCallback(Request $request)
    {
        $code = $request->input('code');
        $state = $request->input('state');

        if (empty($code)) {
            Log::error('微信静默授权回调失败: 缺少code参数');
            return redirect()->route('wechat.service.account.login')
                ->with('error', '微信授权失败，请重试');
        }

        try {
            // 1. 使用code获取access_token
            $appId = config('wechat.app_id');
            $appSecret = config('wechat.app_secret');
            $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";

            $response = file_get_contents($tokenUrl);
            $tokenData = json_decode($response, true);

            if (isset($tokenData['errcode'])) {
                Log::error('获取微信access_token失败', $tokenData);
                return redirect()->route('wechat.service.account.login')
                    ->with('error', '微信授权失败: ' . $tokenData['errmsg']);
            }

            $accessToken = $tokenData['access_token'];
            $openId = $tokenData['openid'];

            // 2. 使用access_token获取用户基本信息
            $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
            $userInfoResponse = file_get_contents($userInfoUrl);
            $userInfo = json_decode($userInfoResponse, true);

            if (isset($userInfo['errcode'])) {
                Log::error('获取微信用户信息失败', $userInfo);
                return redirect()->route('wechat.service.account.login')
                    ->with('error', '获取用户信息失败: ' . $userInfo['errmsg']);
            }

            // 3. 处理用户登录/注册逻辑
            $userData = [
                'nickname' => $userInfo['nickname'] ?? '微信用户',
                'avatar' => $userInfo['headimgurl'] ?? '',
                'gender' => $userInfo['sex'] ?? 0,
                'province' => $userInfo['province'] ?? '',
                'city' => $userInfo['city'] ?? '',
                'country' => $userInfo['country'] ?? '',
                'access_token' => encrypt($tokenData['access_token']),
                'access_token_expires_at' => now()->addHours(2)->subSecond(1),
                'session_key' => $tokenData['session_key'] ?? '',
                'session_expires_at' => now()->addDays(30)
            ];

            // 使用事务确保数据一致性
            DB::transaction(function () use ($openId, $userData, &$user, &$token) {
                $user = WechatServiceAccountUser::updateOrCreate(
                    ['openid' => $openId],
                    $userData
                );
                
                // 生成并存储用户Token
                $token = Str::random(60);
                UserToken::updateOrCreate(
                    ['wechat_user_id' => $user->id],
                    [
                        'token' => $token,
                        'expired_at' => now()->addDays(30)
                    ]
                );
            });

            // 记录完整的用户信息
            Log::debug('WeChat User Object Details (Silent Auth)', [
                'time' => now()->toDateTimeString(),
                'user_id' => $user->id,
                'openid' => $user->openid,
                'user_attributes' => $user->makeHidden([
                    'access_token',
                    'access_token_expires_at'
                ])->toArray(),
                'request_ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ]);

            // 4. 登录用户
            Auth::guard('wechat')->login($user, true);

            // 立即记录登录状态
            Log::debug('After silent login:', [
                'check' => Auth::guard('wechat')->check(),
                'user' => Auth::guard('wechat')->user(),
                'session_id' => session()->getId(),
            ]);
            
            // 将token存入session以便前端使用
            $request->session()->put('wechat_token', $token);
            
            // 调试日志
            Log::debug('WeChat silent login status:', [
                'authenticated' => Auth::guard('wechat')->check(),
                'user_id' => Auth::guard('wechat')->id()
            ]);

            // 检查是否有意图访问的URL
            $intendedUrl = session()->pull('url.intended');
            
            // 获取重定向参数
            $redirectParam = $request->query('redirect');
            
            // 优先使用重定向参数，然后是意图URL，最后是默认页面
            if ($redirectParam) {
                $redirectUrl = $redirectParam;
            } elseif ($intendedUrl && strpos($intendedUrl, '/wechat-service-account/redeem') !== false) {
                $redirectUrl = $intendedUrl;
            } else {
                // 默认跳转到"我的"页面
                $redirectUrl = route('wechat.service.account.my');
            }

            Log::debug('Redirecting to:', ['url' => $redirectUrl]);

            // 微信内特殊处理
            if (strpos($request->userAgent(), 'MicroMessenger') !== false) {
                return redirect($redirectUrl);
            }

            return redirect($redirectUrl);
        } catch (\Exception $e) {
            Log::error('微信静默授权流程异常: ' . $e->getMessage());
            return redirect()->route('wechat.service.account.login')
                ->with('error', '微信授权异常，请重试');
        }
    }

    /**
     * 显示个人中心页面
     */
    public function my(Request $request)
    {
        Log::debug('进入my页面', [
            'check' => Auth::guard('wechat')->check(),
            'user' => Auth::guard('wechat')->user(),
            'session_id' => session()->getId(),
        ]);
        $user = Auth::guard('wechat')->user();
        
        // 如果用户是后台用户(attribute=1)且没有指定mode参数，则显示身份选择页面
        if ($user && $user->attribute == 1 && !$request->has('mode')) {
            return view('wechat.service_account.identity_selection');
        }
        
        // 查询用户的默认收货地址
        $defaultAddress = null;
        if ($user) {
            $defaultAddress = WechatServiceAccountAddress::where('user_id', $user->id)
                ->where('is_default', true)
                ->first();
        }

        return view('wechat.service_account.my', compact('user', 'defaultAddress'));
    }
    
    /**
     * 显示后台管理页面
     */
    public function admin(Request $request)
    {
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否有权限访问后台
        if (!$user || $user->attribute != 1) {
            return redirect()->route('wechat.service.account.my')->with('error', '无权限访问此页面');
        }
        
        // 查询所有订单，排除"未支付"和"已取消"状态，按创建时间倒序排列
        $orders = Order::where('status', '!=', '未支付')
            ->where('status', '!=', '已取消')
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        
        return view('wechat.service_account.admin.dashboard', compact('orders'));
    }

    /**
     * 显示商品库存管理页面
     */
    public function inventory()
    {
        // 获取当前用户
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试访问库存管理页面');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 检查用户是否有权限访问后台
        if ($user->attribute != 1) {
            return redirect()->route('wechat.service.account.my')->with('error', '无权限执行此操作');
        }
        
        // 获取所有商品，按库存数量升序排列（最少库存排在前面）
        $products = Product::orderBy('stock', 'asc')->paginate(10);
        
        return view('wechat.service_account.admin.inventory', compact('products'));
    }

    /**
     * 显示商品编辑页面
     */
    public function editProduct($id)
    {
        // 获取当前用户
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试访问商品编辑页面');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 检查用户是否有权限访问后台
        if ($user->attribute != 1) {
            return redirect()->route('wechat.service.account.my')->with('error', '无权限执行此操作');
        }
        
        // 获取商品信息
        $product = Product::findOrFail($id);
        
        return view('wechat.service_account.admin.product_edit', compact('product'));
    }
    
    /**
     * 更新商品信息
     */
    public function updateProduct(Request $request, $id)
    {
        // 获取当前用户
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试更新商品信息');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 检查用户是否有权限访问后台
        if ($user->attribute != 1) {
            return redirect()->route('wechat.service.account.my')->with('error', '无权限执行此操作');
        }
        
        // 获取商品信息
        $product = Product::findOrFail($id);
        
        // 验证输入数据
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'description' => 'nullable|string|max:1000',
        ]);
        
        // 更新商品信息
        $product->update($validated);
        
        return redirect()->route('wechat.service.account.inventory')
            ->with('success', '商品信息更新成功！');
    }

    /**
     * 获取微信JS-SDK配置
     * 
     * @return array 包含appId、timestamp、nonceStr和signature的数组
     */
    private function getWxJsConfig()
    {
        // 使用正确的环境变量名称
        $appId = env('WECHAT_SERVICE_ACCOUNT_APPID', '');
        $appSecret = env('WECHAT_SERVICE_ACCOUNT_SECRET', '');

        if (empty($appId) || empty($appSecret)) {
            Log::error('微信配置缺失: AppID或AppSecret未设置');
            return [
                'appId' => $appId,
                'timestamp' => time(),
                'nonceStr' => Str::random(16),
                'signature' => '',
            ];
        }

        // 获取jsapi_ticket
        $ticket = $this->getJsApiTicket($appId, $appSecret);

        // 当前URL
        $url = url()->current();

        // 生成配置参数
        $timestamp = time();
        $nonceStr = Str::random(16);

        // 按照微信官方规则生成签名
        // 参考：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
        $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        return [
            'appId' => $appId,
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => $signature,
        ];
    }

    /**
     * 获取微信JS API票据
     * 
     * @param string $appId 微信AppID
     * @param string $appSecret 微信AppSecret
     * @return string jsapi_ticket
     */
    private function getJsApiTicket($appId, $appSecret)
    {
        // 尝试从缓存获取ticket
        $cacheKey = "wechat_jsapi_ticket_$appId";
        $ticket = Cache::get($cacheKey);

        if (!$ticket) {
            // 先获取access_token
            $accessToken = $this->getAccessToken($appId, $appSecret);

            // 使用access_token获取jsapi_ticket
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
            $response = file_get_contents($url);
            $result = json_decode($response, true);

            if (isset($result['ticket'])) {
                $ticket = $result['ticket'];
                // 缓存ticket，有效期7200秒（2小时）
                Cache::put($cacheKey, $ticket, 7000);
            } else {
                Log::error('获取jsapi_ticket失败', $result);
                throw new \Exception('获取jsapi_ticket失败: ' . json_encode($result));
            }
        }

        return $ticket;
    }

    /**
     * 获取微信接口调用凭证
     * 
     * @param string $appId 微信AppID
     * @param string $appSecret 微信AppSecret
     * @return string access_token
     */
    private function getAccessToken($appId, $appSecret)
    {
        // 尝试从缓存获取token
        $cacheKey = "wechat_access_token_$appId";
        $accessToken = Cache::get($cacheKey);

        if (!$accessToken) {
            // 请求微信接口获取access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
            $response = file_get_contents($url);
            $result = json_decode($response, true);

            if (isset($result['access_token'])) {
                $accessToken = $result['access_token'];
                // 缓存access_token，有效期7200秒（2小时）
                Cache::put($cacheKey, $accessToken, 7000);
            } else {
                Log::error('获取access_token失败', $result);
                throw new \Exception('获取access_token失败: ' . json_encode($result));
            }
        }

        return $accessToken;
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        Auth::guard('wechat')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        // 修改为返回首页
        return redirect()->route('wechat.service.account.index');
    }
    
    /**
     * 显示用户卡包页面
     */
    public function wallet()
    {
        $user = Auth::guard('wechat')->user();
        
        if (!$user) {
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 获取用户的会员卡（已使用的会员权益兑换码）
        $memberCards = \App\Models\RedemptionCode::where('used_user_id', $user->id)
            ->where('type', 'time_access')
            ->where('status', 'used')
            ->orderBy('used_at', 'desc')
            ->get();
        
        // 获取用户的兑换历史记录
        $redemptionHistory = \App\Models\RedemptionCode::where('used_user_id', $user->id)
            ->where('status', 'used')
            ->orderBy('used_at', 'desc')
            ->get();
        
        return view('wechat.service_account.wallet', compact('memberCards', 'redemptionHistory'));
    }
    
    /**
     * 显示兑换页面
     */
    public function redeem(Request $request)
    {
        // 获取兑换码参数
        $code = $request->query('code');
        
        // 检查用户是否已登录
        $isAuthenticated = Auth::guard('wechat')->check();
        
        return view('wechat.service_account.redeem', compact('code', 'isAuthenticated'));
    }
    
    /**
     * 处理兑换码提交
     */
    public function redeemSubmit(Request $request)
    {
        try {
            // 检查用户是否已登录
            if (!Auth::guard('wechat')->check()) {
                return response()->json([
                    'success' => false,
                    'message' => '请先登录后再进行兑换操作'
                ]);
            }
            
            // 验证兑换码
            $request->validate([
                'code' => 'required|string|max:255',
            ]);
            
            $code = $request->input('code');
            $user = Auth::guard('wechat')->user();
            
            // 这里应该根据实际的RedemptionCode模型进行验证和处理
            // 以下是示例逻辑，需要根据实际情况调整
            $redemptionCode = \App\Models\RedemptionCode::where('code', $code)
                ->where('status', 'unused')
                ->where('expired_at', '>', now())
                ->first();
            
            if (!$redemptionCode) {
                return response()->json([
                    'success' => false,
                    'message' => '兑换码无效或已过期'
                ]);
            }
            
            // 如果是time_access类型，处理会员权限
            if ($redemptionCode->type === 'time_access') {
                // 解析metadata获取天数和权限等级
                // 确保metadata是字符串类型才进行json_decode
                $metadata = is_string($redemptionCode->metadata) 
                    ? json_decode($redemptionCode->metadata, true) 
                    : ($redemptionCode->metadata ?? []);
                $days = $metadata['days'] ?? 30;
                $permissionLevel = $metadata['permission_level'] ?? 'basic';
                
                // 查询用户已兑换的time_access类型兑换码中未过期的记录
                $userExistingValidRedemption = \App\Models\RedemptionCode::where('used_user_id', $user->id)
                    ->where('type', 'time_access')
                    ->where('status', 'used')
                    ->where('expired_at', '>', now())
                    ->orderBy('expired_at', 'desc')
                    ->first();
                
                // 计算新的过期时间
                if ($userExistingValidRedemption) {
                    // 用户已有未过期的会员权益，确保expired_at是Carbon对象
                    $existingExpireTime = is_string($userExistingValidRedemption->expired_at) 
                        ? Carbon::parse($userExistingValidRedemption->expired_at) 
                        : $userExistingValidRedemption->expired_at;
                    // 从现有过期时间的次日开始累加天数，并设置为当天的23:59:59
                    $newExpireTime = $existingExpireTime->addDays($days)->endOfDay();
                    $message = '兑换成功！会员权益已在当前有效期基础上延长';
                } else {
                    // 用户没有未过期的会员权益，从当前日期计算并设置为当天23:59:59
                    $newExpireTime = now()->addDays($days)->endOfDay();
                    $message = '兑换成功！会员权益已激活';
                }
                
                // 更新兑换码状态，包括status、used_at和used_user_id字段
                $redemptionCode->status = 'used';
                $redemptionCode->used_at = now();
                $redemptionCode->used_user_id = $user->id; // 写入当前用户的ID号
                
                // 更新兑换码的过期时间为计算后的新过期时间
                $redemptionCode->expired_at = $newExpireTime;
                $redemptionCode->save();
                
                return response()->json([
                    'success' => true,
                    'message' => $message,
                    'memberInfo' => [
                        'days' => $days,
                        'permissionLevel' => $permissionLevel,
                        'expireTime' => $newExpireTime->format('Y-m-d H:i:s')
                    ]
                ]);
            } else {
                // 其他类型的兑换码处理逻辑
                return response()->json([
                    'success' => false,
                    'message' => '不支持的兑换码类型'
                ]);
            }
        } catch (\Exception $e) {
            Log::error('兑换码处理失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '兑换处理失败，请稍后重试'
            ]);
        }
    }
    
    /**
     * 显示订单详情页面
     */
    public function showOrder($orderId)
    {
        // 获取当前用户
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试访问订单详情');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 检查用户是否有权限访问后台
        if ($user->attribute != 1) {
            // 普通用户只能查看自己的订单
            $order = Order::with(['items.product', 'shippingAddress'])
                ->where('id', $orderId)
                ->where('wechat_service_account_user_id', $user->id)
                ->firstOrFail();
        } else {
            // 管理员可以查看所有订单
            $order = Order::with(['items.product', 'shippingAddress'])
                ->where('id', $orderId)
                ->firstOrFail();
        }
        
        return view('wechat.service_account.admin.order_detail', compact('order'));
    }

    /**
     * 处理订单发货
     */
    public function shipOrder(Request $request, $orderId)
    {
        // 获取当前用户
        $user = Auth::guard('wechat')->user();
        
        // 检查用户是否已认证
        if (!$user) {
            Log::warning('未认证用户尝试发货');
            return redirect()->route('wechat.service.account.login')->with('error', '请先登录');
        }
        
        // 检查用户是否有权限访问后台
        if ($user->attribute != 1) {
            return redirect()->route('wechat.service.account.my')->with('error', '无权限执行此操作');
        }
        
        // 验证输入
        $request->validate([
            'logistics_company' => 'required|string|max:255',
            'tracking_number' => 'required|string|max:255',
        ]);
        
        // 获取订单及关联信息
        $order = Order::with(['items.product', 'user'])->findOrFail($orderId);
        
        // 更新订单物流信息
        $order->update([
            'logistics_company' => $request->input('logistics_company'),
            'tracking_number' => $request->input('tracking_number'),
            'shipped_at' => now(),
            'status' => '已发货'
        ]);
        
        // 发送微信模板消息通知
        try {
            $this->sendShippingNotification($order);
        } catch (\Exception $e) {
            Log::error('发送微信模板消息失败', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
        
        // 重定向回订单详情页面并显示成功消息
        return redirect()->route('wechat.service.account.orders.show', $orderId)
            ->with('success', '发货信息已成功提交！');
    }
    
    /**
     * 发送订单发货微信模板消息通知
     */
    private function sendShippingNotification($order)
    {
        // 获取微信用户
        $wechatUser = $order->user;
        if (!$wechatUser || !$wechatUser->openid) {
            Log::warning('订单用户没有绑定微信openid', ['order_id' => $order->id]);
            return;
        }
        
        // 获取订单商品名称（合并多个商品）
        $productNames = $order->items->map(function ($item) {
            return $item->product_name;
        })->implode(', ');
        
        // 构造模板消息数据
        $messageData = [
            'touser' => $wechatUser->openid,
            'template_id' => 'jJmAHcmzKPEe_1MD2zOdxnOgL1tGtcKLyhP9K1BGo_0',
            'data' => [
                'character_string2' => [
                    'value' => $order->order_number,
                ],
                'thing4' => [
                    'value' => $order->logistics_company,
                ],
                'character_string3' => [
                    'value' => $order->tracking_number,
                ],
                'time5' => [
                    'value' => $order->shipped_at->format('Y-m-d H:i:s'),
                ],
                'thing7' => [
                    'value' => $productNames,
                ],
            ],
        ];
        
        // 发送模板消息
        try {
            $app = \Overtrue\LaravelWeChat\EasyWeChat::officialAccount();
            $client = $app->getClient();
            
            // 使用 POST 请求发送模板消息
            $response = $client->postJson('cgi-bin/message/template/send', $messageData);
            $result = $response->toArray();
            
            Log::info('微信模板消息发送结果', [
                'order_id' => $order->id,
                'result' => $result
            ]);
            
            // 检查发送结果
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                Log::error('微信模板消息发送失败', [
                    'order_id' => $order->id,
                    'error_code' => $result['errcode'],
                    'error_message' => $result['errmsg'] ?? '未知错误'
                ]);
            }
        } catch (\Exception $e) {
            Log::error('发送微信模板消息异常', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
}